package com.tom.demo.security;

import com.tom.demo.common.entity.SysUser;
import com.tom.demo.common.enumeration.ResponseEnum;
import com.tom.demo.common.exception.CustomException;
import com.tom.demo.common.exception.ServiceException;
import com.tom.demo.mapper.SysMenuMapper;
import com.tom.demo.mapper.SysRoleMapper;
import com.tom.demo.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: LanQiang
 * @Date: 2023/01/16/17:24
 * @Description: 实现SpringSecurity的接口UserDetailsService
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    /**
     * 这里封装了用户表单输入的用户名（账号）
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username){
        //查询用户信息
        SysUser sysUser = sysUserMapper.findByUserName(username);
        //查询用户的角色名称和权限名称，这里的权限暂时用菜单代替了
        Set<String> roles;
        Set<String> rolesKeys;
        Set<String> permissions;
        //判断当前的登录人是不是admin,也就是系统管理员，这个admin拥有全部的权限
        if("admin".equals(username)){
            roles = sysRoleMapper.findByRoleKey(null);
            permissions = sysMenuMapper.findByPerms(null);
        }else {
            roles = sysRoleMapper.findByRoleKey(sysUser.getUserId());
            permissions = sysMenuMapper.findByPerms(sysUser.getUserId());
        }
        //特殊处理一下角色，加上固定前缀，security底层规定
        rolesKeys = roles.stream().map(roleKey -> "ROLE_" + roleKey).collect(Collectors.toSet());
        //把数据封装成UserDetails返回
        return new DetailsUser(sysUser,rolesKeys,permissions);
    }
}